<template>
    <view class="mt-4 pb-4">
        <view class="mt-8 mx-4 flex items-center">
            <view class="mr-4 text-lg font-bold">我的车辆</view>
            <nut-button size="mini" type="primary" @click="goToLicensePage('add')">
                创建车辆信息
            </nut-button>
        </view>
        <view class="flex flex-col items-center">
            <template v-if="licenseRecords.length">
                <LicensePlate
                    v-for="license in licenseRecords"
                    :key="license.id"
                    :licenseInfo="license"
                    class="mt-4"
                    @edit="goToLicensePage('edit', license.license)"
                    @delete="handleDelete(license)"
                />
            </template>
            <template v-else>
                <view class="m-8 text-gray-400">暂无车辆信息～</view>
            </template>
        </view>
    </view>
</template>

<script lang="ts" setup>
import Taro from '@tarojs/taro'
import { ref } from 'vue'

import LicensePlate from '@/components/LicensePlate.vue'
import { licenseRecordUserList, licenseRecordDelete } from '@/api/license'

const goToLicensePage = (pageType: string, license?: string) => {
    Taro.navigateTo({
        url: `/pages/license/index?pageType=${pageType}&license=${license}`
    })
}

interface ILicenseRecord {
    license: string
    id: string
}
const licenseRecords = ref<ILicenseRecord[]>([])
const queryUserLicenseList = async () => {
    try {
        const res = await licenseRecordUserList()

        licenseRecords.value = res.result || []
    } catch (error) {
        licenseRecords.value = []
    }
}

const handleDelete = async (licenseInfo: ILicenseRecord) => {
    await licenseRecordDelete({ license: licenseInfo.license })
    queryUserLicenseList()
}

Taro.useDidShow(() => {
    queryUserLicenseList()
})
</script>

<style lang="less"></style>
